package com.cloud.weixin.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.cloud.common.core.utils.LocalDateTimeUtils;
import com.cloud.weixin.project.cons.WxCons;
import com.cloud.weixin.project.mapper.WxUserMapper;
import com.cloud.weixin.project.model.entity.WxAutoReply;
import com.cloud.weixin.project.model.entity.WxUser;
import com.cloud.weixin.project.service.IWxAutoReplyService;
import com.cloud.weixin.project.service.IWxMsgService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 订阅处理
 */
@Slf4j
@Component
@AllArgsConstructor
public class SubscribeHandler extends AbstractHandler {

    @Autowired
    private IWxAutoReplyService wxAutoReplyService;
    @Autowired
    private IWxMsgService wxMsgService;
    @Resource
    private WxUserMapper wxUserMapper;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {
        log.info("新关注用户 OPENID: " + wxMessage.getFromUser());
        // 获取微信用户基本信息
        try {
            WxMpUser userWxInfo = weixinService.getUserService()
                    .userInfo(wxMessage.getFromUser(), null);
            if (userWxInfo != null) {
                // TODO 添加关注用户到本地数据库
                WxUser wxUser = SqlHelper.getObject(wxUserMapper.selectList(Wrappers.<WxUser>lambdaQuery()
                        .eq(WxUser::getOpenId, userWxInfo.getOpenId())));
                if (wxUser == null) {//第一次关注
                    wxUser = new WxUser();
                    wxUser.setSubscribeNum(1);
                    setWxUserValue(wxUser, userWxInfo);
                    wxUserMapper.insert(wxUser);
                } else {//曾经关注过
                    wxUser.setSubscribeNum(wxUser.getSubscribeNum() + 1);
                    setWxUserValue(wxUser, userWxInfo);
                    wxUserMapper.updateById(wxUser);
                }
                //发送关注消息
                List<WxAutoReply> listWxAutoReply = wxAutoReplyService.list(Wrappers.<WxAutoReply>query()
                        .lambda().eq(WxAutoReply::getType, WxCons.WX_AUTO_REPLY_TYPE_SUBSCRIBE));
                WxMpXmlOutMessage wxMpXmlOutMessage = MsgHandler.getWxMpXmlOutMessage(wxMessage, listWxAutoReply, wxUser, wxMsgService);
                return wxMpXmlOutMessage;
            }
        } catch (Exception e) {
            log.error("用户关注出错：" + e.getMessage());
        }
        return null;
    }

    public static void setWxUserValue(WxUser wxUser, WxMpUser userWxInfo) {
        wxUser.setAppType(WxCons.WX_APP_TYPE_MP);
        wxUser.setSubscribe(userWxInfo.getSubscribe() ? WxCons.SUBSCRIBE_TYPE_YES : WxCons.SUBSCRIBE_TYPE_NO);
        wxUser.setSubscribeScene(userWxInfo.getSubscribeScene());
        wxUser.setOpenId(userWxInfo.getOpenId());
        wxUser.setSubscribeTime(LocalDateTimeUtils.timestamToDatetime(userWxInfo.getSubscribeTime() * 1000));
        wxUser.setNickName(userWxInfo.getNickname());
        wxUser.setSex(userWxInfo.getSex());
        wxUser.setCity(userWxInfo.getCity());
        wxUser.setCountry(userWxInfo.getCountry());
        wxUser.setProvince(userWxInfo.getProvince());
        wxUser.setLanguage(userWxInfo.getLanguage());
        wxUser.setRemark(userWxInfo.getRemark());
        wxUser.setHeadImgUrl(userWxInfo.getHeadImgUrl());
        wxUser.setUnionId(userWxInfo.getUnionId());
        wxUser.setGroupId(JSON.toJSONString(userWxInfo.getGroupId()));
        wxUser.setTagIdList(Arrays.deepToString(userWxInfo.getTagIds()));
        wxUser.setQrSceneStr(userWxInfo.getQrSceneStr());
    }


}
